//pages/exam/exam.js
const common = require("../../../utils/zstz.js");
//获取应用实例
const app = getApp().globalData;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    timer: '', //定时器名字
    timer3: '', //3秒间隔定时器
    delayTimer: '', //动效延迟的定时器
    countDownNum: 10, //设置倒计时初始值
    rotateLeft: 'rotateLeft',
    rotateRight: 'rotateRight',
    index: 0, //题目的索引
    selfClass: '', //选中答案对错状态显示
    correctClass: '', //正确答案的状态显示
    alreadyClick: false, //记录已经点击过了
    titleMove: 'titleMove', //标题出现动效类名
    titleNoMove: 'titleNoMove', //标题题号出现动效类名
    answersMove: 'answersMove', //答案出现动效类名
    circleMove: 'circleMove', //计时器的动效类名
    subject: [],
    title: '', //本次显示的标题
    answer: [], //本次显示的答案
    correct: '', //本次正确的答案
    clickId: 0, //点击答案的下标
    addScore: 0, //答题得分
    qCataId: '',
    cataname: '',
    hide: 'hide'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    //动态修改标题
    wx.setNavigationBarTitle({
      title: options.cataname
    })
    that.setData({
      countDownNum: app.countDownNum,
      qCataId: options.qCataId,
      cataname: options.cataname,
      name: wx.getStorageSync('userInfo').nickName,
      avatar: wx.getStorageSync('userInfo').avatarUrl,

    });
    that.getQuestions();
    that.data.delayTimer = setTimeout(function () {
      //show = true; 说明题出现了才能点击
      that.countDown();
    }, 1200)
    that.countChange();
  },

  //10秒倒计时定时器
  countDown: function () {
    let that = this;
    let countDownNum = that.data.countDownNum; //获取倒计时初始值
    //如果将定时器设置在外面，那么用户就看不到countDownNum的数值动态变化，所以要把定时器存进data里面
    that.data.timer = setInterval(function () { //这里把setInterval赋值给变量名为timer的变量
      if (countDownNum == 1 && that.data.alreadyClick == false) {
        //当倒计时结束并且没有点击答案，就显示正确答案
        that.setData({
          correctClass: 'true',
          alreadyClick: true //说明已经点击过了
        })
      }
      if (countDownNum == 0) {
        that.cancelCurrent(); //取消当前的题目和动效状态
      } else {
        countDownNum--;
        that.setData({
          countDownNum: countDownNum
        });
      }
    }, 1000)
  },

  //更换题目间隔3秒的定时器
  countChange: function () {
    let that = this;
    that.data.timer3 = setInterval(function () { //这里把setInterval赋值给变量名为timer的变量
      //更换下一题数据，动效，倒计时定时器
      that.startCurrent();
    }, 13600) //整体切换题目的定时器
  },

  //点击选中答案
  clickAnswer: function (event) {
    let that = this,
      index = event.currentTarget.dataset.index,
      score; //获取当前点击的元素下标
    console.log(that.data.alreadyClick)
    if (that.data.alreadyClick) {
      return; //说明已经点击过了 
    }
    score = 200 - (10 - that.data.countDownNum) * 10;
    that.setData({
      clickId: index,
      alreadyClick: true
    });
    // console.log(event.currentTarget.dataset.choose, event.currentTarget.dataset.correct);
    if (event.currentTarget.dataset.choose == event.currentTarget.dataset.correct) {
      //说明自己答对了
      that.data.addScore = that.data.addScore + score;
      that.setData({
        selfClass: 'true',
        addScore: that.data.addScore,
      });
    } else {
      //要显示正确答案
      that.setData({
        selfClass: 'false',
        correctClass: 'true'
      })
    }
    //点击完之后 即可消除定时器，进入下一题（调用和倒计时一样的函数即可）
    clearTimeout(that.data.delayTimer)
    clearInterval(that.data.timer) //清空10秒间隔的定时器
    clearInterval(that.data.timer3) //清空10秒间隔的定时器
    if (that.data.index == (common.subjectSum - 1)) {
      setTimeout(() => {
        wx.redirectTo({
          url: '../selfPractise/practise?score=' + that.data.addScore + '&qCataId=' + that.data.qCataId + '&cataname=' + that.data.cataname + '&myAvatar=' + that.data.avatar + '&myName=' + that.data.name
        })
      }, 2000)
      return
    }
    //隔两秒取消当前的数据和动效
    setTimeout(() => {
      that.cancelCurrent(); //显示完正确答案之后延迟消失
    }, 1500)
    setTimeout(() => {
      that.startCurrent(); //消失完之后要有个延迟 执行出现的动效，不然消失和出现直接无缝衔接没有过度的效果，太生硬
      that.countChange();
    }, 2000)
  },

  //取消当前的数据和动效状态
  cancelCurrent() {
    //题目不可点击
    let that = this;
    that.data.index++; //题目索引加1
    if (that.data.index == common.subjectSum) {
      clearInterval(that.data.timer);
      clearInterval(that.data.timer3);
      setTimeout(() => {
        wx.redirectTo({
          url: '../selfPractise/practise?score=' + that.data.addScore + '&qCataId=' + that.data.qCataId + '&cataname=' + that.data.cataname + '&myAvatar=' + that.data.avatar + '&myName=' + that.data.name
        })
      }, 2000)
      return;
    }
    that.setData({
      selfClass: '', //每换一题所有答案状态清空
      correctClass: '',
      rotateLeft: '',
      rotateRight: '',
      titleMove: '',
      titleNoMove: '',
      answersMove: '',
      circleMove: '',
      countDownNum: app.countDownNum,
      index: that.data.index,
    });
    clearInterval(that.data.timer) //清空10秒倒计时的定时器
  },

  //当前数据显示和动效出现
  startCurrent() {
    let that = this;
    that.setData({
      rotateLeft: 'rotateLeft',
      rotateRight: 'rotateRight',
      titleMove: 'titleMove',
      titleNoMove: 'titleNoMove',
      answersMove: 'answersMove',
      circleMove: 'circleMove',
      index: that.data.index,
      title: that.data.subject[that.data.index].title,
      answer: that.data.subject[that.data.index].answer,
      correct: that.data.subject[that.data.index].correct
    });
    that.data.delayTimer = setTimeout(function () {
      that.setData({
        alreadyClick: false, //延迟执行  防止题没有出来就选上答案
      })
      that.countDown(); //执行下一题的计时定时器
    }, 1200)
  },

  //请求题目
  getQuestions() {
    let that = this,
      openId = wx.getStorageSync('openid'),
      token = wx.getStorageSync('token');
    let url = common.baseUrl + 'game/startSP?openId=' + openId + '&token=' + token + '&qCataId=' + that.data.qCataId;
    wx.request({
      url: url,
      method: 'get',
      data: {
        fid: app.fid,
        uid: wx.getStorageSync('cxid'),
        wxType: app.wxTypes[11].id
      },
      success: (res) => {
        console.log(res)
        if (res.data.success) {
          let arr = res.data.data,
            data = [];
          for (let index = 0; index < arr.length; index++) {
            let obj = {},
              answer = [];
            obj.title = arr[index].quesetion;
            obj.answer = [arr[index].optionA, arr[index].optionB, arr[index].optionC, arr[index].optionD];
            if (arr[index].rightAnswer == 'A') {
              obj.correct = arr[index].optionA
            }
            if (arr[index].rightAnswer == 'B') {
              obj.correct = arr[index].optionB
            }
            if (arr[index].rightAnswer == 'C') {
              obj.correct = arr[index].optionC
            }
            if (arr[index].rightAnswer == 'D') {
              obj.correct = arr[index].optionD
            }
            data.push(obj);
          }
          that.setData({
            subject: data
          });
          console.log(that.data.subject)
          that.setData({
            title: that.data.subject[that.data.index].title,
            answer: that.data.subject[that.data.index].answer,
            correct: that.data.subject[that.data.index].correct,
          });
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let that = this;
    clearTimeout(that.data.delayTimer)
    clearInterval(that.data.timer3) //清空10秒间隔的定时器
    clearTimeout(that.data.time)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
  
})